// 搜索管理
import React, { useState, useEffect } from 'react';
import { Table, Space, Button, Switch, Modal, message, ConfigProvider } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { TableRowSelection } from 'antd/es/table/interface';
import { ExclamationCircleFilled } from '@ant-design/icons';
import AddorRev from './oSearchChild/AddorRev';
import '../../css/operation.css'
import zh_CN from 'antd/es/locale/zh_CN';
import { getSreach, delSreach } from '../../../api/opreationApi'
interface DataType {
  key: React.Key;
  searchId: number;
  searchName: string;
  searchLocation: number;
  searchState: number
}


export default function OperationSearch() {
  const [sreachData, setSreachData] = useState()
  const [pageSize, setPageSize] = useState<number>(7) //每页条数
  const [currentPage, setCurrentPage] = useState<number>(1) //当前第几页
  const [total, setTotal] = useState<number>()//总条数
  const [upTotal, setUpTotal] = useState<any>(null)//已上架条数
  // 拿初始数据、查询、排序
  const getData = () => {
    getSreach({
      pageSize, currentPage
    }).then(res => {
      setSreachData(res.data.searches)
      setTotal(res.data.total)
      setUpTotal(res.data.upTotal)
    })
  }

  // 监听调用
  useEffect(() => {
    getData()
  }, [pageSize, pageSize, currentPage])

  //页码或 pageSize 改变的回调，参数是改变后的页码及每页条数
  const pageChange = (page: number, pageSize: number) => {
    setPageSize(pageSize)
    setCurrentPage(page)
  }
  // 表格
  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'searchId',
    },
    {
      title: '关键词名字',
      dataIndex: 'searchName',
    },
    {
      title: '位置',
      dataIndex: 'searchLocation',
    },
    {
      title: '是否上架',
      dataIndex: 'searchState',
      render: (_, record) => (
        <Switch checked={record.searchState === 1 ? true : false} />
      ),
    },
    {
      title: '操作',
      dataIndex: 'address',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" className='edmit' onClick={() => rev(record)}>编辑</Button>
          <Button id='del' onClick={() => showConfirm(record)}>删除</Button>
        </Space >
      ),
    },
  ];

  const rowSelection: TableRowSelection<DataType> = {
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: 'odd',
        text: 'Select Odd Row',
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return false;
            }
            return true;
          });
        },
      },
      {
        key: 'even',
        text: 'Select Even Row',
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return true;
            }
            return false;
          });
        },
      },
    ],
  };


  // 操作部分
  // （1）删除
  // 删除弹框
  const { confirm } = Modal;
  const showConfirm = (record?: any) => {
    confirm({
      title: '提示:',
      icon: <ExclamationCircleFilled />,
      content: '您确定要删除吗？删除后无法恢复！',
      cancelText: '取消',
      okText: '确认',
      onOk() {
        delSreach({ id: record.searchId }).then(res => { getData() })
        message.success('删除成功！')
      },
    });
  };

  // （2）添加和编辑共用弹框
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);//是否显示对话框
  const [head, setHead] = useState<string | null>(null);
  const [nowRev, setNowRev] = useState<DataType | null>(null)
  // 添加
  const add = (): void => {
    setIsModalOpen(true)
    setHead('添加')
  }
  // 编辑
  const rev = (record: any): void => {
    setIsModalOpen(true)
    setNowRev(record)
    setHead('编辑')
  }

  // 自定义添加编辑弹框消失
  const modalClose = () => {
    setIsModalOpen(false);
  }

  return <div>
    {/* 头部标题 */}
    <p className='head opHead'>搜索管理</p>
    {/* 表格整体 */}
    <div className='table'>
      {/* 表格操作 */}
      <div className='tableOpreation bottomItems'>
        <p style={{ fontSize: '16px', fontWeight: '600' }}>最多同时上架6个关键词</p>
        {/* 添加按钮 */}
        <div className='add-wrap'>
          <Button className='add' onClick={add}>添加</Button>
        </div>
      </div>
      {/* 表格 */}
      <ConfigProvider locale={zh_CN}>
        <Table
          rowKey={item => item.searchId}
          rowSelection={rowSelection}
          columns={columns}
          dataSource={sreachData}
          pagination={{
            position: ['bottomRight'],
            defaultPageSize: 5,
            pageSizeOptions: [2, 3, 5, 6],
            showQuickJumper: true,
            showSizeChanger: true,
            total: total,
            onChange: pageChange,
            pageSize: pageSize,
            showTotal: (total: number) => (`共有 ${total} 条数据`)
          }} />
      </ConfigProvider>
    </div>
    {/* 增加编辑共用弹框 */}
    <AddorRev nowRev={nowRev} upTotal={upTotal} getData={getData} modalClose={modalClose} isModalOpen={isModalOpen} head={head}></AddorRev>
  </div>;
};
